package com.xhwl.data.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xhwl.common.dto.cent.sdata.AccountOrganizationDTO;
import com.xhwl.common.exception.BusinessException;
import com.xhwl.common.pojo.ResultJson;
import com.xhwl.common.pojo.cent.sdata.AccountOrganization;
import com.xhwl.common.query.cent.sdata.OrganizationQuery;
import com.xhwl.data.dao.IAccountOrganizationDao;
import com.xhwl.data.service.IAccountOrganizationService;
import com.xhwl.data.service.IOrganizationTypeService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * @Author: JCccc
 * @Description:
 * @Date: Create in 17:10 2020/12/2
 */
@Service
public class AccountOrganizationServiceImpl extends ServiceImpl<IAccountOrganizationDao, AccountOrganization> implements IAccountOrganizationService {

    @Autowired
    private IAccountOrganizationDao accountOrganizationDao;

    @Autowired
    private IOrganizationTypeService organizationTypeService;

    private static final Logger log = LoggerFactory.getLogger(AccountOrganizationServiceImpl.class);

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteBatch(List<AccountOrganization> accountOrganizationList) {

        try {
            for (AccountOrganization accountOrganization : accountOrganizationList) {
                QueryWrapper<AccountOrganization> deleteWrapper = new QueryWrapper();
                deleteWrapper.eq("account_id", accountOrganization.getAccountId());
                deleteWrapper.eq("organization_id", accountOrganization.getOrganizationId());
                deleteWrapper.eq("enterprise_id", accountOrganization.getEnterpriseId());
                accountOrganizationDao.delete(deleteWrapper);
            }
        } catch (Exception e) {
            TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new BusinessException("账号组织表删除失败");
        }


    }

	@Override
	public List<AccountOrganization> findByAccountId(Integer accountId) {

    	if(null == accountId){
    		log.warn("帐号id为空");
    		return Collections.emptyList();
		}
    	QueryWrapper<AccountOrganization> queryWrapper = new QueryWrapper<>();
    	queryWrapper.eq("account_id", accountId);
		return accountOrganizationDao.selectList(queryWrapper);
	}

    @Override
    public ResultJson removeOrg(AccountOrganizationDTO accountOrganizationDTO) {
        try {
            accountOrganizationDao.remove(accountOrganizationDTO);
        }catch (Exception e){
            e.printStackTrace();
            return ResultJson.fail("删除失败");
        }
        return ResultJson.success();
    }

    @Override
    public List<AccountOrganizationDTO> groupSpaceList(List<Integer> accountIds) {

        if(CollectionUtils.isEmpty(accountIds)){
            return Collections.emptyList();
        }
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.in("account_id", accountIds);
        accountOrganizationQueryWrapper.in("type", organizationTypeService.spaceIds());
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        if(accountOrganizations.isEmpty()){
            return Collections.emptyList();
        }
        Map<Integer, List<Integer>> collect = accountOrganizations.stream().collect(Collectors.groupingBy(AccountOrganization::getAccountId, Collectors.mapping(AccountOrganization::getOrganizationId, Collectors.toList())));

        List<AccountOrganizationDTO> result = new ArrayList<>(collect.size());
        for (Map.Entry<Integer, List<Integer>> integerListEntry : collect.entrySet()) {
            AccountOrganizationDTO accountOrganizationDTO = new AccountOrganizationDTO();
            accountOrganizationDTO.setAccountId(integerListEntry.getKey());
            accountOrganizationDTO.setOrganizationId(integerListEntry.getValue());
            result.add(accountOrganizationDTO);
        }
        return result;
    }

    @Override
    public List<Integer> accountIds(OrganizationQuery organizationQuery) {
        QueryWrapper<AccountOrganization> accountOrganizationQueryWrapper = new QueryWrapper<>();
        accountOrganizationQueryWrapper.select("account_id").groupBy("account_id");
        organizationQueryHandler(organizationQuery, accountOrganizationQueryWrapper);
        List<AccountOrganization> accountOrganizations = accountOrganizationDao.selectList(accountOrganizationQueryWrapper);
        return accountOrganizations.stream().map(i -> i.getAccountId()).collect(Collectors.toList());
    }

    private void organizationQueryHandler(OrganizationQuery organizationQuery, QueryWrapper<AccountOrganization> queryWrapper){

        if(null == organizationQuery){
            queryWrapper.eq("id", -1);
            return;
        }
        if(!CollectionUtils.isEmpty(organizationQuery.ids)){
            queryWrapper.in("organization_id", organizationQuery.ids);
        }
        if(!CollectionUtils.isEmpty(organizationQuery.types)){
            queryWrapper.in("type", organizationQuery.types);
        }
        if(!CollectionUtils.isEmpty(organizationQuery.enterpriseIds)){
            queryWrapper.in("enterprise_id", organizationQuery.enterpriseIds);
        }
    }

}
